var _pageTarget = $("#content");
function fullScreen() {
    var el = document.documentElement;
    var rfs = el.requestFullScreen || el.webkitRequestFullScreen;
    if (typeof rfs != "undefined" && rfs) {
        rfs.call(el)
    } else if (typeof window.ActiveXObject != "undefined") {
        var wscript = new ActiveXObject("WScript.Shell");
        if (wscript != null) {
            wscript.SendKeys("{F11}")
        }
    } else if (el.msRequestFullscreen) {
        el.msRequestFullscreen()
    } else if (el.oRequestFullscreen) {
        el.oRequestFullscreen()
    } else {
        swal({
            title: "浏览器不支持全屏调用！",
            text: "请更换浏览器或按F11键切换全屏！",
            type: "error",
            timer: 3000
        }).then(function () { });
    }
}

function loadData(url,showitem) {
    $.ajax({
        cache: false,
        type: "GET",
        url: url,
        data: "",
//		async: false,
        beforeSend: function(XMLHttpRequest) {
            layer.load();
        },
        error: function(request) {
            layer.closeAll('loading');
            layer.alert("您的网络不给力，请稍后再试。", '提示');
            return false;

        },
        success: function(data) {
            layer.closeAll('loading');
            if (showitem != '') {
                $("#"+showitem).html(data);
            } else {
                $("#content").html(data);
            }
        }
    });
}


$(function () {
    $(document).off("click", 'button.btn[data-target="sheldan"]').on("click", 'button.btn[data-target="sheldan"]', function () {
        var _me = $(this).data();
        $.get(_me.url).done(function (d) {
            swal({
                animation: false,
                width: _me.width,
                background: (_me.background || '#fff'),
                padding: (_me.padding || 20),
                showConfirmButton: false,
                html: d,
                onOpen: function () {
                    $(".swal2-content").css({ "font-size": "14px", "text-align": "initial" });
                },
                onClose: function () {
                    $(".swal2-content").css({ "font-size": "18px", "text-align": "center" });
                }
            });
        });
    });
});



$(function () {
    $(document).off("click", 'button.btn[data-target="viwendy"]').on("click", 'button.btn[data-target="viwendy"]', function () {
        var _this = $(this);
        var _url = $(this).data();
        var tit = $(this).data('title');
        var pageURL = $().data('url');
        $.get(_url).done(function (d) {
            swal({
                html: d,
                width: (_url.width || 1111),
                showConfirmButton: false,
                onOpen: function () {
                    $(".swal2-content .card-title").html(tit);
                    $('.datepicker').datetimepicker({
                        format: 'YYYY-MM-DD',
                        icons: {
                            time: "fa fa-clock-o",
                            date: "fa fa-calendar",
                            up: "fa fa-chevron-up",
                            down: "fa fa-chevron-down",
                            previous: 'fa fa-chevron-left',
                            next: 'fa fa-chevron-right',
                            today: 'fa fa-screenshot',
                            clear: 'fa fa-trash',
                            close: 'fa fa-remove'
                        }
                    });
                    $('.selectpicker').selectpicker().val((function () {
                        return $('.selectpicker').data('val')
                    })()).selectpicker('refresh');
                    $('#summernote').createNote();
                    $('input[type="file"].file').createUpload();
                    $("form.pageForm").createSubmit(function () {
                        // _this.ajaxTables(pageURL, {}, null, null);
                    });
                    $('.checkbox input[type="checkbox"]').oncheckbox();
                },
                onClose: function () {
                    $('.selectpicker').selectpicker('destroy');
                    $('#summernote').summernote('destroy');
                    $('input[type="file"].file').fileinput('destroy');
                    $('form.pageForm').validator("destroy");
                }
            });
        });
    });
});


(function ($) {
    $.fn.extend({
        donetyping: function (callback, timeout) {
            timeout = timeout || 1e3;
            var timeoutReference,
                doneTyping = function (el) {
                    if (!timeoutReference) return;
                    timeoutReference = null;
                    callback.call(el);
                };
            return this.each(function (i, el) {
                var $el = $(el);
                $el.is(':input') && $el.on('keyup keypress', function (e) {
                    if (e.type == 'keyup' && e.keyCode != 8) return;
                    if (timeoutReference) clearTimeout(timeoutReference);
                    timeoutReference = setTimeout(function () {
                        doneTyping(el);
                    }, timeout);
                }).on('blur', function () {
                    doneTyping(el);
                });
            });
        },
        ajaxTables: function (url, columns, params, options) {
            var configs = {
                dom: '<"container-fluid"<"row"<"col-lg-12"t>><"row bottomPager"<"col-lg-5 col-sm-12"i><"col-lg-7 col-sm-12"p>>>',
                bPaginate: true,
                language: lang,
                responsive: true,
                bSort: true,
                bDestroy: true,
                autoWidth: true,
                processing: false,
                serverSide: true,
                searching: false,
                orderMulti: false,
                bLengthChange: false,
                order: [],
                iDisplayLength: 20,
                pagingType: "full_numbers",
                columnDefs: [{
                    "targets": 'nosort',
                    "orderable": false
                }],
                columns: columns,
                fnInitComplete: function () {
                    $(document).off("click", 'button.btn[data-target="winModal"]').on("click", 'button.btn[data-target="winModal"]', function () {
                        $(".main-panel,.wrapper").scrollTop(0);
                        var _me = $(this).data();
                        $.get(_me.url).done(function (d) {
                            swal({
                                animation: false,
                                width: _me.width,
                                background: (_me.background || '#fff'),
                                padding: (_me.padding || 20),
                                showConfirmButton: false,
                                html: d,
                                onOpen: function () {
                                    $(".swal2-content").css({ "font-size": "14px", "text-align": "initial" });
                                },
                                onClose: function () {
                                    $(".swal2-content").css({ "font-size": "18px", "text-align": "center" });
                                }
                            });
                        });
                    });
                }
            };
            $(this).dataTable($.extend(configs, {
                columns: columns,
                ajax: _ajax
            }, options)).api();

            function _ajax(data, callback, settings) {
                var _d = {};
                _d.navTabId = Math.random();
                _d.pageSize = data.length; //页面显示记录条数，在页面显示每页显示多少项的时候
                _d.pageCurrent = (data.start / data.length) + 1; //当前页码
                if (data.order.length > 0) {
                    //let idx;
                    var idx;
                    $.each(data.order, function (x, y) {
                        idx = columns[y.column];
                        y.sortField = (idx.alias || idx.data);
                    });
                    console.log(data.order);
                    _d.columnSort = JSON.stringify(data.order)
                }
                $.extend(_d, params);
                $.ajax({
                    type: "POST",
                    url: url,
                    data: _d,
                    success: function (json) {
                        if (json.statusCode === 200) {
                            var res = {};
                            res.draw = data.draw;
                            res.recordsTotal = json.total; //返回数据全部记录
                            res.recordsFiltered = json.total; //后台不实现过滤功能，每次查询均视作全部结果
                            res.data = json.data;
                            callback(res);
                            return false;
                        }
                    }
                });
            };
        },
        createPager: function (columns, params, options) {
            tools.initFormExtendedDatetimepickers();
            if ($(this).length == 0) return false;
            $(this).each(function () {
                var _this = $(this);
                var pageURL = _this.data("url");
                $('.datepicker').datetimepicker({
                    format: 'YYYY-MM-DD',
                    icons: {
                        time: "fa fa-clock-o",
                        date: "fa fa-calendar",
                        up: "fa fa-chevron-up",
                        down: "fa fa-chevron-down",
                        previous: 'fa fa-chevron-left',
                        next: 'fa fa-chevron-right',
                        today: 'fa fa-screenshot',
                        clear: 'fa fa-trash',
                        close: 'fa fa-remove'
                    }
                });
                _this.css("width", "100%").ajaxTables(pageURL, columns, params, options);
                _this.find('tbody').on('click', 'tr[role="row"]', function () {
                    $(this).toggleClass('warning');
                });
                $(document).off("click", ".toolbar button.btn").on("click", ".toolbar button.btn", function () {
                    $(".main-panel,.wrapper").scrollTop(0);
                    var _elem = $(this);
                    var _data = _elem.data();
                    var custom = _data.options;
                    if (!custom || !custom.target) return false;
                    var onKey = custom.target.toUpperCase();
                    if (onKey === "FIND") {
                        var __def = {};
                        if (!params) params = {};
                        var __k = $("#keyWord"),
                            __s = $("#startDate"),
                            __f = $("#finishDate"),
                            __m = $("#ddlModeType"),
                            __n = $("#serverType");
                        if (__k.length == 1) $.extend(__def, params, {
                            k: $.trim(__k.val())
                        });
                        if (__s.length == 1) $.extend(__def, params, {
                            s: $.trim(__s.val())
                        });
                        if (__f.length == 1) $.extend(__def, params, {
                            f: $.trim(__f.val())
                        });
                        if (__m.length == 1) $.extend(__def, params, {
                            m: $.trim(__m.val())
                        });
                        if (__n.length == 1) $.extend(__def, params, {
                            n: $.trim(__n.val())
                        });
                        _this.ajaxTables(pageURL, columns, __def, options);
                    }
                    if (onKey === "RESET") {
                        $(".toolbar input[type='text']").val(" ");
                        _this.ajaxTables(pageURL, columns, null, options);
                    }
                    if (onKey === "ADD") {
                        if (!custom.url || custom.url.length == 0) return false;
                        var tit = $(this).data('title');
                        $.get(custom.url).done(function (d) {
                            swal({
                                html: d,
                                width: (custom.width || 1111),
                                showConfirmButton: false,
                                onOpen: function () {
                                    $(".swal2-content .card-title").html(tit);
                                    $('.datepicker').datetimepicker({
                                        format: 'YYYY-MM-DD',
                                        icons: {
                                            time: "fa fa-clock-o",
                                            date: "fa fa-calendar",
                                            up: "fa fa-chevron-up",
                                            down: "fa fa-chevron-down",
                                            previous: 'fa fa-chevron-left',
                                            next: 'fa fa-chevron-right',
                                            today: 'fa fa-screenshot',
                                            clear: 'fa fa-trash',
                                            close: 'fa fa-remove'
                                        }
                                    });
                                    $('.selectpicker').selectpicker();
                                    $('#summernote').createNote();
                                    $('input[type="file"].file').createUpload();
                                    $("form.pageForm").createSubmit(function () {
                                        _this.ajaxTables(pageURL, columns, null, options);
                                    });
                                    $('.checkbox input[type="checkbox"]').oncheckbox();
                                },
                                onClose: function () {
                                    $('.selectpicker').selectpicker('destroy');
                                    $('#summernote').summernote('destroy');
                                    $('input[type="file"].file').fileinput('destroy');
                                    $('form.pageForm').validator("destroy");
                                }
                            });
                        });
                    }
                    if (onKey === "EDIT") {
                        if (!custom.url || custom.url.length == 0) return false;
                        var selected = _this.find("tbody>tr[role='row'].warning");
                        if (selected.length !== 1) {
                            swal('单项操作！', '请选中单行需要进行操作项！', 'warning');
                            return false;
                        }
                        //var _url = custom.url + (selected.children("td.hidden:eq(0)").text());
                        var _url = custom.url + '?id='+ (selected.children("td.text-center:eq(0)").text());
                        var tit = $(this).data('title');
                        $.get(_url).done(function (d) {
                            swal({
                                html: d,
                                width: (custom.width || 1111),
                                showConfirmButton: false,
                                onOpen: function () {
                                    $(".swal2-content .card-title").html(tit);
                                    $('.datepicker').datetimepicker({
                                        format: 'YYYY-MM-DD',
                                        icons: {
                                            time: "fa fa-clock-o",
                                            date: "fa fa-calendar",
                                            up: "fa fa-chevron-up",
                                            down: "fa fa-chevron-down",
                                            previous: 'fa fa-chevron-left',
                                            next: 'fa fa-chevron-right',
                                            today: 'fa fa-screenshot',
                                            clear: 'fa fa-trash',
                                            close: 'fa fa-remove'
                                        }
                                    });
                                    $('.selectpicker').selectpicker().val((function () {
                                        return $('.selectpicker').data('val')
                                    })()).selectpicker('refresh');
                                    $('#summernote').createNote();
                                    $('input[type="file"].file').createUpload();
                                    $("form.pageForm").createSubmit(function () {
                                        _this.ajaxTables(pageURL, columns, null, options);
                                    });
                                    $('.checkbox input[type="checkbox"]').oncheckbox();
                                },
                                onClose: function () {
                                    $('.selectpicker').selectpicker('destroy');
                                    $('#summernote').summernote('destroy');
                                    $('input[type="file"].file').fileinput('destroy');
                                    $('form.pageForm').validator("destroy");
                                }
                            });
                        });
                    }

                    if (onKey === "EDITS") {
                        var ids = $("#ids").val();
                        if (ids == "" || ids == null || ids == undefined) {
                            swal('单项操作！', '请选中单行需要进行操作项！', 'warning');
                            return false;
                        }
                        var obj = JSON.parse(ids);
                        if (!custom.url || custom.url.length == 0) return false;

                        var _url = custom.url + '?id='+ obj.rid + '&gid=' + obj.gid;
                        var tit = $(this).data('title');
                        $.get(_url).done(function (d) {
                            swal({
                                html: d,
                                width: (custom.width || 1111),
                                showConfirmButton: false,
                                onOpen: function () {
                                    $(".swal2-content .card-title").html(tit);
                                    $('.datepicker').datetimepicker({
                                        format: 'YYYY-MM-DD',
                                        icons: {
                                            time: "fa fa-clock-o",
                                            date: "fa fa-calendar",
                                            up: "fa fa-chevron-up",
                                            down: "fa fa-chevron-down",
                                            previous: 'fa fa-chevron-left',
                                            next: 'fa fa-chevron-right',
                                            today: 'fa fa-screenshot',
                                            clear: 'fa fa-trash',
                                            close: 'fa fa-remove'
                                        }
                                    });
                                    $('.selectpicker').selectpicker().val((function () {
                                        return $('.selectpicker').data('val')
                                    })()).selectpicker('refresh');
                                    $('#summernote').createNote();
                                    $('input[type="file"].file').createUpload();
                                    $("form.pageForm").createSubmit(function () {
                                        _this.ajaxTables(pageURL, columns, null, options);
                                    });
                                    $('.checkbox input[type="checkbox"]').oncheckbox();
                                },
                                onClose: function () {
                                    $('.selectpicker').selectpicker('destroy');
                                    $('#summernote').summernote('destroy');
                                    $('input[type="file"].file').fileinput('destroy');
                                    $('form.pageForm').validator("destroy");
                                }
                            });
                        });
                    }

                    if (onKey === "DELETE") {
                        if (!custom.url || custom.url.length == 0) return false;
                        var selected = _this.find("tbody>tr[role='row'].warning");
                        if (selected.length === 0) {
                            swal('批量操作！', '请选中至少一行需要进行操作项！', 'warning');
                            return false;
                        }
                        var ids = [];
                        selected.each(function () {
                            ids.push($(this).children("td.text-center:eq(0)").text());
                        });
                        swal({
                            type: 'question',
                            title: '批量操作？',
                            text: "请确认是否继续此项操作，此操作不可逆！",
                            showCancelButton: true
                        }).then(function () {
                            $.post(custom.url, {
                                ids: ids.join(",")
                            }, function (d) {
                                if (d.statusCode === 200) {
                                    swal('操作成功！', d.message, 'success');
                                    _this.ajaxTables(pageURL, columns, null, options);
                                    return false;
                                }
                                swal('操作失败！', d.message, 'error');
                            });
                        }, function (dismiss) { });
                    }

                    if (onKey === "CHECKBOX") {
                        if (!custom.url || custom.url.length == 0) return false;
                        var selected = _this.find("tbody>tr[role='row'].warning");
                        if (selected.length === 0) {
                            swal('批量操作！', '请选中至少一行需要进行操作项！', 'warning');
                            return false;
                        }
                        var ids = [];
                        selected.each(function () {
                            ids.push($(this).children("td.text-center:eq(0)").text());
                        });
                        var _url = custom.url;
                        var tit = $(this).data('title');
                        $.get(_url).done(function (d) {
                            swal({
                                html: d,
                                width: (custom.width || 1111),
                                showConfirmButton: false,
                                onOpen: function () {
                                    $(".swal2-content .card-title").html(tit);
                                    $('#players').val(ids.join(","));
                                    $('.datepicker').datetimepicker({
                                        format: 'YYYY-MM-DD',
                                        icons: {
                                            time: "fa fa-clock-o",
                                            date: "fa fa-calendar",
                                            up: "fa fa-chevron-up",
                                            down: "fa fa-chevron-down",
                                            previous: 'fa fa-chevron-left',
                                            next: 'fa fa-chevron-right',
                                            today: 'fa fa-screenshot',
                                            clear: 'fa fa-trash',
                                            close: 'fa fa-remove'
                                        }
                                    });
                                    $('.selectpicker').selectpicker().val((function () {
                                        return $('.selectpicker').data('val')
                                    })()).selectpicker('refresh');
                                    $('#summernote').createNote();
                                    $('input[type="file"].file').createUpload();
                                    $("form.pageForm").createSubmit(function () {
                                        _this.ajaxTables(pageURL, columns, null, options);
                                    });
                                    $('.checkbox input[type="checkbox"]').oncheckbox();
                                },
                                onClose: function () {
                                    $('.selectpicker').selectpicker('destroy');
                                    $('#summernote').summernote('destroy');
                                    $('input[type="file"].file').fileinput('destroy');
                                    $('form.pageForm').validator("destroy");
                                }
                            });
                        });
                    }


                    if (onKey === "DELETES") {
                        var ids = $("#ids").val();
                        if (ids == "" || ids == null || ids == undefined) {
                            swal('单项操作！', '请选中单行需要进行操作项！', 'warning');
                            return false;
                        }
                        var obj = JSON.parse(ids);
                        if (!custom.url || custom.url.length == 0) return false;
                        var _url = custom.url + '?id='+ obj.rid + '&gid=' + obj.gid;
                        swal({
                            type: 'question',
                            title: '确定删除操作？',
                            text: "请确认是否继续此项操作，此操作不可逆！",
                            showCancelButton: true
                        }).then(function () {
                            $.post(_url, {
                                //ids: ids.join(",")
                            }, function (d) {
                                if (d.statusCode === 200) {
                                    swal('操作成功！', d.message, 'success');
                                    _this.ajaxTables(pageURL, columns, null, options);
                                    return false;
                                }
                                swal('操作失败！', d.message, 'error');
                            });
                        }, function (dismiss) { });
                    }


                    if (onKey === "CLEAR") {
                        if (!custom.url || custom.url.length == 0) return false;
                        var selected = _this.find("tbody>tr[role='row']");
                        if (selected.length === 0) {
                            swal('清理操作！', '没有任何可清理操作项！', 'warning');
                            return false;
                        }
                        swal({
                            type: 'question',
                            title: '清理操作？',
                            text: "请确认是否继续此项操作，此操作不可逆！",
                            showCancelButton: true
                        }).then(function () {
                            var __def = {};
                            if (!params) params = {};
                            var __k = $("#keyWord"),
                                __s = $("#startDate"),
                                __f = $("#finishDate");
                            if (__k.length == 1) $.extend(__def, params, {
                                k: $.trim(__k.val())
                            });
                            if (__s.length == 1) $.extend(__def, params, {
                                s: $.trim(__s.val())
                            });
                            if (__f.length == 1) $.extend(__def, params, {
                                f: $.trim(__f.val())
                            });
                            $.post(custom.url, __def, function (d) {
                                if (d.statusCode === 200) {
                                    swal('操作成功！', d.message, 'success');
                                    _this.ajaxTables(pageURL, columns, __def, options);
                                    return false;
                                }
                                swal('操作失败！', d.message, 'error');
                            });
                        }, function (dismiss) { });
                    }

                    //提点奖金审核通过
                    if (onKey === "CHECK") {
                        if (!custom.url || custom.url.length == 0) return false;
                        var selected = _this.find("tbody>tr[role='row'].warning");
                        if (selected.length === 0) {
                            swal('审核操作！', '请选中至少一行需要审核的操作项！', 'warning');
                            return false;
                        }
                        var ids = [];
                        selected.each(function () {
                            ids.push($(this).children("td.text-center:eq(0)").text());
                        });
                        swal({
                            type: 'question',
                            title: '审核操作？',
                            text: "请确认是否继续通过审核，此操作不可逆！",
                            showCancelButton: true
                        }).then(function () {
                            $.post(custom.url, {
                                ids: ids.join(",")
                            }, function (d) {
                                if (d.statusCode === 200) {
                                    swal('审核成功！', d.message, 'success');
                                    _this.ajaxTables(pageURL, columns, null, options);
                                    return false;
                                }
                                swal('审核失败！', d.message, 'error');
                            });
                        }, function (dismiss) { });
                    }


                    //标记提款申请
                    if (onKey === "REMIT") {
                        if (!custom.url || custom.url.length == 0) return false;
                        var selected = _this.find("tbody>tr[role='row'].warning");
                        if (selected.length === 0) {
                            swal('标记操作！', '请选中至少一行需要标记的操作项！', 'warning');
                            return false;
                        }
                        var ids = [];
                        selected.each(function () {
                            ids.push($(this).children("td.text-center:eq(0)").text());
                        });
                        swal({
                            type: 'question',
                            title: '标记操作？',
                            text: "请确认是否继续标记提款申请记录，此操作不可逆！",
                            showCancelButton: true
                        }).then(function () {
                            $.post(custom.url, {
                                ids: ids.join(",")
                            }, function (d) {
                                if (d.statusCode === 200) {
                                    swal('标记完成！', d.message, 'success');
                                    _this.ajaxTables(pageURL, columns, null, options);
                                    return false;
                                }
                                swal('标记失败！', d.message, 'error');
                            });
                        }, function (dismiss) { });
                    }


                    //标记红包管理状态
                    if (onKey === "REDPACKET") {
                        if (!custom.url || custom.url.length == 0) return false;
                        var selected = _this.find("tbody>tr[role='row'].warning");
                        if (selected.length === 0) {
                            swal('红包设置！', '请选中至少一行需要设置的操作项！', 'warning');
                            return false;
                        }
                        var ids = [];
                        selected.each(function () {
                            ids.push($(this).children("td.text-center:eq(0)").text());
                        });
                        swal({
                            type: 'question',
                            title: '设置操作？',
                            text: "请确认是否继续设置红包状态！",
                            showCancelButton: true
                        }).then(function () {
                            $.post(custom.url, {
                                ids: ids.join(",")
                            }, function (d) {
                                if (d.statusCode === 200) {
                                    swal('设置完成！', d.message, 'success');
                                    _this.ajaxTables(pageURL, columns, null, options);
                                    return false;
                                }
                                swal('设置失败！', d.message, 'error');
                            });
                        }, function (dismiss) { });
                    }


                    //删除系统消息提示
                    if (onKey === "READ") {
                        if (!custom.url || custom.url.length == 0) return false;
                        var selected = _this.find("tbody>tr[role='row'].warning");
                        if (selected.length === 0) {
                            swal('删除操作！', '请选中至少一行需要标记的操作项！', 'warning');
                            return false;
                        }
                        var ids = [];
                        selected.each(function () {
                            ids.push($(this).children("td.text-center:eq(0)").text());
                        });
                        swal({
                            type: 'question',
                            title: '删除操作？',
                            text: "请确认是否删除提示消息！",
                            showCancelButton: true
                        }).then(function () {
                            $.post(custom.url, {
                                ids: ids.join(",")
                            }, function (d) {
                                if (d.statusCode === 200) {
                                    swal('删除完成！', d.message, 'success');
                                    _this.ajaxTables(pageURL, columns, null, options);
                                    return false;
                                }
                                swal('删除失败！', d.message, 'error');
                            });
                        }, function (dismiss) { });
                    }



                });
            });
        },

        oncheckbox: function () {
            if ($(this).length == 0) return false;
            $(this).each(function () {
                var $val = $(this).val();
                if ($val == '0') {
                    $(this).attr("checked", "checked");
                } else {
                    $(this).removeAttr("checked");
                }
                $(this).click(function () {
                    $val = $(this).val();
                    if ($val == '0') {
                        $(this).removeAttr("checked").attr("value", 1);
                    } else {
                        $(this).attr({
                            "checked": "checked",
                            "value": 0
                        });
                    }
                });

            });
        },
        createNote: function () {
            if ($(this).length == 0) return false;
            $(this).each(function () {
                var _this = $(this);
                _this.summernote({
                    lang: 'zh-CN',
                    placeholder: '发布内容...',
                    height: 250,
                    callbacks: {
                        onImageUpload: function (files) {
                            var formData = new FormData();
                            formData.append('file', files[0]);
                            formData.append('file_id', Math.random());
                            formData.append('uploadExt', "summernote");
                            $.ajax({
                                url: '/webui/ajax-upload/',
                                type: 'POST',
                                data: formData,
                                processData: false,
                                contentType: false,
                                success: function (d) {
                                    if (d && d.data) {
                                        _this.summernote('insertImage', d.data.filename, 'img');
                                    }
                                }
                            });
                        }
                    }
                });
            });
        },
        createUpload: function () {
            if ($(this).length == 0) return false;
            $(this).each(function () {
                var files = [],
                    names = [],
                    arrs = [],
                    _initialPreview = [],
                    _initialPreviewConfig = [];
                var fv = $(this);
                var hd = fv.parents('.form-group.uplbox').next('input[type="hidden"].uplhidden');
                var ps = hd.val();
                if (ps.length > 0) {
                    var im = ps.split(';');
                    var _vir = '';
                    for (var i in im) {
                        _vir = common.GetUrlRelativePath(im[i]);
                        names.push(im[i]);
                        files.push({
                            filename: im[i],
                            filepath: _vir
                        });
                        _initialPreviewConfig.push({
                            key: _vir,
                            extra: {
                                files: JSON.stringify([{
                                    filepath: _vir
                                }])
                            }
                        });
                        _initialPreview.push(im[i]);
                    }
                }
                fv.fileinput({
                    language: 'zh',
                    theme: 'fa',
                    browseClass: 'btn btn-primary',
                    removeClass: 'btn btn-danger',
                    cancelClass: 'btn btn-warning',
                    uploadClass: 'btn btn-success',
                    uploadUrl: '/webui/ajax-upload/',
                    deleteUrl: '/webui/remove-uploaded/',
                    allowedFileExtensions: ['jpg', 'png', 'gif'],
                    dropZoneTitle: '拖拽或选择上传图片，支持多图片同时上传',
                    overwriteInitial: false,
                    uploadExtraData: {
                        uploadExt: hd.attr('name')
                    },
                    maxFileSize: 1024,
                    minFileCount: 1,
                    maxFileCount: 10,
                    showCaption: false,
                    initialPreviewAsData: true,
                    allowedFileTypes: ['image'],
                    initialPreview: _initialPreview,
                    initialPreviewConfig: _initialPreviewConfig
                }).on("fileuploaded", function (event, data, previewId, idx) {
                    var d = data.response;
                    if (!d) {
                        swal('操作失败！', '上传处理失败', 'warning');
                        return false;
                    }
                    if (d.statusCode == 200) {
                        $("#" + previewId).find("button.kv-file-remove").attr("data-path", d.data.filepath);
                        files.push(d.data);
                        names.push(d.data.filename);
                        hd.val(names.join(';'));
                    } else {
                        swal('操作失败！', d.message, 'warning');
                        return false;
                    }
                }).on("filesuccessremove", function (event, uploadid, idx) {
                    var vKey = $("#" + uploadid).find("button.kv-file-remove").data('path');
                    for (var i in files) {
                        if (files[i].filepath == vKey) {
                            removeFiles([files[i]]);
                            names.splice(i, 1);
                            files.splice(i, 1);
                            break;
                        }
                    }
                    hd.val(names.join(';'));
                }).on("fileclear", function () {
                    removeFiles(files);
                    names = [], files = [], arrs = [];
                    hd.val(null);
                }).on("filepredelete", function (event, vKey, jqXHR, extraData) {
                    for (var i in files) {
                        if (files[i].filepath == vKey) {
                            names.splice(i, 1);
                            files.splice(i, 1);
                        }
                    }
                    hd.val(names.join(';'));
                });
            });

            function removeFiles(arr, fn) {
                $.post("/webui/remove-uploaded/", {
                    files: JSON.stringify(arr)
                }, fn);
            }
        },
        createSubmit: function (callback) {
            if ($(this).length == 0) return false;
            $(this).each(function () {
                $(this).on('validation', function (e, current) {
                    var field = $(current.element).closest('div');
                    if (current.isValid) {
                        if (field.hasClass('has-error')) field.removeClass('has-error');
                        if (field.find('.form-control-feedback').length === 0) field.append('<span class="material-icons form-control-feedback">done</span>');
                        else field.find('.form-control-feedback').text('done');
                        field.addClass('has-success');
                    } else {
                        if (field.hasClass('has-success')) field.removeClass('has-success');
                        if (field.find('.form-control-feedback').length === 0) field.append('<span class="material-icons form-control-feedback">clear</span>');
                        else field.find('.form-control-feedback').text('clear');
                        field.addClass('has-error');
                    }
                }).on('valid.form', function (e, form) {
                    $(this).ajaxSubmit({
                        restForm: true,
                        clearForm: true,
                        beforeSubmit: function () {
                            $(form).find('.has-success').removeClass('has-success');
                            $(form).find('.form-control-feedback').remove('.form-control-feedback');
                        },
                        success: function (d) {
                            if (d.statusCode === 200) {
                                $(".main-panel,.wrapper").scrollTop(0);
                                swal('操作成功！', d.message, 'success');
                                if (callback) {
                                    callback();
                                }
                                return false;
                            }
                            swal('操作失败！', d.message, 'error');
                        }
                    });
                });
            });
        }
    });
})(jQuery);


$(function () {
    $sidebar = $('#sidebar');
    $sidebar.find(".nav > li").each(function () {
        $(this).on("click", function () {
            $(this).siblings("li").removeClass("active");
            $(this).addClass("active").find(".has-sub > .nav-submenu > li").each(function () {
                $(this).on("click", function () {
                    $(this).addClass("active");
                });
            });
        });
    });

    $('div[data-target="ajaxLoad"]').each(function () {
        var url = $(this).data('url');
        url += (url.indexOf('?') === -1 ? "?" : "&") + "_=" + Math.random();
        $(this).load(url);
    });

    var uip = $(".user").attr("data-ip");

    if (uip === "") {
        tools.showNotification('top', 'right', '安全提示，初次登录系统，请立即修改你的个人登录密码与交易密码，以防他人恶意操作！', 'danger');
    }

    $(document).off("click", 'a[data-target="navTab"]').on("click", 'a[data-target="navTab"]', function () {
        var opts = $(this).data();
        if (!opts.url || opts.url.length == 0) return false;
        _pageTarget.load(opts.url + (opts.url.indexOf('?') === -1 ? "?" : "&") + "moduleId=" + opts.id + "&_=" + Math.random());
    });
    $(document).off("click", '.fixed-plugin a').on("click", '.fixed-plugin a', function (event) {
        // Alex if we click on switch, stop propagation of the event, so the dropdown will not be hide, otherwise we set the  section active
        if ($(this).hasClass('switch-trigger')) {
            if (event.stopPropagation) {
                event.stopPropagation();
            } else if (window.event) {
                window.event.cancelBubble = true;
            }
        }
    });
    $(document).off("click", '.fixed-plugin .active-color span').on("click", '.fixed-plugin .active-color span', function (event) {
        $full_page_background = $('.full-page-background');
        $(this).siblings().removeClass('active');
        $(this).addClass('active');
        var new_color = $(this).data('color');
        if ($sidebar.length != 0) {
            $sidebar.attr('data-active-color', new_color);
        }
        if ($full_page.length != 0) {
            $full_page.attr('filter-color', new_color);
        }
        if ($sidebar_responsive.length != 0) {
            $sidebar_responsive.attr('data-color', new_color);
        }
    });
    $(document).off("click", '.fixed-plugin .background-color span').on("click", '.fixed-plugin .background-color span', function (event) {
        $(this).siblings().removeClass('active');
        $(this).addClass('active');
        var new_color = $(this).data('color');
        if ($sidebar.length != 0) {
            $sidebar.attr('data-background-color', new_color);
        }
    });
    $(document).off("click", '.fixed-plugin .img-holder').on("click", '.fixed-plugin .img-holder', function (event) {
        $full_page_background = $('.full-page-background');
        $(this).parent('li').siblings().removeClass('active');
        $(this).parent('li').addClass('active');
        var new_image = $(this).find("img").attr('src');
        if ($sidebar_img_container.length != 0 && $('.switch-sidebar-image input:checked').length != 0) {
            $sidebar_img_container.fadeOut('fast', function () {
                $sidebar_img_container.css('background-image', 'url("' + new_image + '")');
                $sidebar_img_container.fadeIn('fast');
            });
        }
        if ($full_page_background.length != 0 && $('.switch-sidebar-image input:checked').length != 0) {
            var new_image_full_page = $('.fixed-plugin li.active .img-holder').find('img').data('src');
            $full_page_background.fadeOut('fast', function () {
                $full_page_background.css('background-image', 'url("' + new_image_full_page + '")');
                $full_page_background.fadeIn('fast');
            });
        }
        if ($('.switch-sidebar-image input:checked').length == 0) {
            var new_image = $('.fixed-plugin li.active .img-holder').find("img").attr('src');
            var new_image_full_page = $('.fixed-plugin li.active .img-holder').find('img').data('src');
            $sidebar_img_container.css('background-image', 'url("' + new_image + '")');
            $full_page_background.css('background-image', 'url("' + new_image_full_page + '")');
        }
        if ($sidebar_responsive.length != 0) {
            $sidebar_responsive.css('background-image', 'url("' + new_image + '")');
        }
    });
    $(document).off("click", '#btnSearch').on("click", '#btnSearch', function (event) {
        var txtSearch = $.trim($("input[name='txtSearch']:visible").val());
        var regx = /^\d{3,5}$/;
        if (!regx.test(txtSearch)) {
            tools.showNotification('top', 'center', '操作失败，请输入有效格式的玩家ID');
            return false;
        }
        $.ajax({
            type: "GET",
            url: "/accountsinfo/userinfo?id=" + txtSearch,
            dataType: "json",
            success: function (json) {
                if (json.statusCode === 200) {
                    var d = json.data;
                    //var html = "<p class='text-left'>玩家标识：" + d.UserID + "<br/>玩家昵称：" + d.NickName + "<br/>账号状态：" + (d.Nullity == 0 ? "正常" : "停用") + "<br/>钻石数量：" + d.Card + " <i class='fa fa-diamond display: inline-block; margin: 15px auto; position: fixed; transition: all 0.5s ease-in-out 0s; z-index: 1031; top: 20px; left: 0px; right: 0px;nd'></i><br/>注册日期：" + d.RegisterDate + "<br/>登录日期：" + d.LastLogonDate + "</p>";
                    var html = "<p class='text-left'>玩家标识：" + d.UserID + "<br/>玩家昵称：" + d.NickName + "<br/>玩家类型：" + d.isRobot + "<br/>钻石数量：" + d.Card + " <i class='fa fa-diamond'></i><br/>金币数量：" + d.Coin + " <i class='fa fa-database'></i><br/>注册日期：" + d.RegisterDate + "<br/>注册地址：" + d.Addr +"</p>";
                    swal('玩家资料', html, 'info');
                    return false;
                }
                if (json.statusCode === 300) {
                    swal('玩家资料', json.message, 'info');
                    return false;
                }
                swal('操作失败！', json.message, 'error');
            }
        });
    });
    $(document).off("toggle", "#fullscan").on("click", "#fullscan", function (event) {
        var _this = $(this);
        if (_this.attr("data-full") == "no") {
            _this.attr("data-full", 'yes');
            fullScreen();
        } else {
            exitFullScreen();
            _this.attr("data-full", 'no');
        }
    });
    $(document).off("click", '#signout').on("click", '#signout', function (event) {
        swal({
            type: 'question',
            title: '退出系统？',
            text: "请确认，是否确定退出当前已登录账号！",
            showCancelButton: true
        }).then(function () {
            swal({
                title: "安全退出！",
                text: "已成功安全退出系统，3秒后自动跳转！",
                type: "success",
                allowOutsideClick: false,
                allowEscapeKey: false,
                timer: 3000,
                onOpen: function () {
                    swal.showLoading()
                }
            }).then(function () {
                window.location.href = "/site/logout";
            }, function (dismiss) {
                if (dismiss === 'timer') {
                    window.location.href = "/site/logout";
                }
            });
        }, function (dismiss) { });
    });
    $(document).off("change", '.switch-sidebar-image input').on("change", '.switch-sidebar-image input', function (event) {
        $full_page_background = $('.full-page-background');
        $input = $(this);
        if ($input.is(':checked')) {
            if ($sidebar_img_container.length != 0) {
                $sidebar_img_container.fadeIn('fast');
                $sidebar.attr('data-image', '#');
            }
            if ($full_page_background.length != 0) {
                $full_page_background.fadeIn('fast');
                $full_page.attr('data-image', '#');
            }
            background_image = true;
        } else {
            if ($sidebar_img_container.length != 0) {
                $sidebar.removeAttr('data-image');
                $sidebar_img_container.fadeOut('fast');
            }
            if ($full_page_background.length != 0) {
                $full_page.removeAttr('data-image', '#');
                $full_page_background.fadeOut('fast');
            }
            background_image = false;
        }
    });
    $(document).off("change", '.switch-sidebar-mini input').on("change", '.switch-sidebar-mini input', function (event) {
        if (md.misc.sidebar_mini_active == true) {
            $('body').removeClass('sidebar-mini');
            md.misc.sidebar_mini_active = false;
            $('.sidebar>.sidebar-wrapper,.main-panel,.wrapper').perfectScrollbar({ suppressScrollX: true });
        } else {
            $('.sidebar .collapse').collapse('hide').on('hidden.bs.collapse', function () {
                $(this).css('height', 'auto');
            });
            $('.sidebar>.sidebar-wrapper,.main-panel,.wrapper').perfectScrollbar('destroy');
            setTimeout(function () {
                $('body').addClass('sidebar-mini');
                $('.sidebar .collapse').css('height', 'auto');
                md.misc.sidebar_mini_active = true;
            }, 300);
        }
        $(".main-panel,.wrapper").scrollTop(0);
        var simulateWindowResize = setInterval(function () {
            window.dispatchEvent(new Event('resize'));
        }, 180);
        setTimeout(function () {
            clearInterval(simulateWindowResize);
        }, 1000);
    });
});